import { Controller } from 'egg';

export default class RightsController extends Controller {
  // 获取所有权限列表
  public async allRights() {
    const { ctx } = this;
    try {
      const rights = await ctx.service.rights.getAllRights();
      ctx.success(rights);
    } catch (e) {
      ctx.error(500, e.message);
    }
  }
  // 获取权限列表(带查询条件)
  public async index() {
    const { ctx } = this;
    try {
      if (JSON.stringify(ctx.query) !== '{}') {
        const rights = await ctx.service.rights.getRights(ctx.query);
        ctx.success(rights);
      } else {
        let rights = await ctx.service.rights.getAllRights();
        // 找出一级权限下的二级权限或者二级权限下的三级权限，都套在level === 0的一级权限里面
        rights = rights.filter((outItem: any) => {
          rights.forEach((inItem: any) => {
            if (outItem.id === inItem.pid) {
              outItem.children ? '' : outItem.children = [];
              outItem.children.push(inItem);
            }
          });
          return outItem.level === 0;
        });
        ctx.success(rights);
      }
    } catch (e) {
      ctx.error(500, e.message);
    }
  }
  // 获取单个权限信息
  public async rightsInfo() {
    const { ctx } = this;
    const { id } = ctx.params;
    try {
      const rights = await ctx.service.rights.getRightsInfo(id);
      ctx.success(rights);
    } catch (e) {
      ctx.error(400, e.message);
    }
  }
  // 新增权限
  public async addRights() {
    const { ctx } = this;
    const obj = ctx.request.body;
    try {
      const rights = await ctx.service.rights.addRights(obj);
      ctx.success(rights);
    } catch (e) {
      if (e.errors) {
        ctx.error(400, e.errors);
      } else {
        ctx.error(400, e.message);
      }
    }
  }
  // 删除权限
  public async destroy() {
    const { ctx } = this;
    const { id } = ctx.params;
    try {
      const rights = await ctx.service.rights.destroy(id);
      ctx.success(rights);
    } catch (e) {
      ctx.error(400, e.message);
    }
  }
  // 编辑用户
  public async update() {
    const { ctx } = this;
    const obj = ctx.request.body;
    const { id } = ctx.params;
    try {
      const rights = await ctx.service.rights.updateRights(id, obj);
      ctx.success(rights);
    } catch (e) {
      if (e.errors) {
        ctx.error(400, e.errors);
      } else {
        ctx.error(400, e.message);
      }
    }
  }
}
